package com.kinon.tyjaccount.view;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.tyjaccount.Constatus;
import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.data.DataModel;
import com.kinon.tyjaccount.data.UPacketFactory;
import com.kinon.tyjaccount.entity.WucanEntity;
import com.kinon.tyjaccount.fragment.DingdanFragment;
import com.kinon.tyjaccount.fragment.JiesuanFragment;
import com.kinon.tyjaccount.fragment.ShezhiFragment;
import com.kinon.tyjaccount.fragment.WucanFragment;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.MyFragmentReplace;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.SharedPreferencesUtil;
import com.kinon.tyjaccount.uitl.SoundPoolManage;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.ICheckFileCallback;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.ISendCallback;
import sunmi.ds.data.DataPacket;

public class MainActivity extends FragmentActivity {

	public static Activity context;
	/** 早餐 */
	private RadioButton rb_zaocan;
	/** 午餐 */
	private static RadioButton rb_wucan;
	/**晚餐*/
	private static RadioButton rb_wancan;
	/** 取餐 */
	private static RadioButton rb_qucan;
	/** 结算 */
	private RadioButton rb_jiesuan;
	/**订单*/
	private RadioButton rb_dingdan;
	/**打印*/
	private RadioButton rb_daying;
	/** 设置 */
	private RadioButton rb_shezhi;
	private TextView tv_time;
	private TextView tv_hint;
	private boolean isEndHandler=false;

	/**副屏相关参数*/
	private int IS_CURRENT_PAGE = 2;

	private static final String SHOW_IMG_LIST_ID = "SHOW_IMG_LIST_ID";
	private static final String WELCOME_IMG_ID = "WELCOME_IMG_ID";

	private final static String SHOW_VIDEO_LIST_DATA_ID = "SHOW_VIDEO_LIST_DATA_ID";
	private final static String SHOW_IMGS_LIST_DATA_ID = "SHOW_IMGS_LIST_DATA_ID";
	public static long taskId;
	public static String pathBig = Environment.getExternalStorageDirectory().getPath() + "/dcim/caizhengting.png";
//   public static String pathBig = Environment.getExternalStorageDirectory().getPath() +"/big.png";
	DSKernel mDSKernel;// SDK核心类
	DataPacket dsPacket;
    //午餐显示的人数
	public static int amount=0;
	public static ArrayList<WucanEntity> infolist=new ArrayList<WucanEntity>();

	//自定义广播
	private UrgentBroadcastReceiver broadcast=new UrgentBroadcastReceiver();
	
//	Window window;  

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//加载音频
		SoundPoolManage.getInstance(this);
		context=this;
		getLunchNum();
		initSDK();
		initRes();

	}
	private void getLunchNum(){
		if(NetWorkUtil.isNetwork(MainActivity.this)==false)
		{
			Toast.makeText(MainActivity.this, "当前网络不可用",
					Toast.LENGTH_SHORT).show();
			return;
		}
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		String token = sp.getString("data", "");
		HttpTools httpTools=new HttpTools(MainActivity.this);
		httpTools.getLunchNum(token,new JsonGetLunchNum());
	}
	private class JsonGetLunchNum extends JsonHttpResponseHandler{

		@Override
		public void onSuccess(JSONObject response) {
			super.onSuccess(response);
//			Log.e("lh", response.toString());
			try {
				boolean code=response.getBoolean("code");
				String msg=response.getString("msg");
				if(code==true){
					int data=response.getInt("data");
					amount=data;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(Throwable e, JSONObject errorResponse) {
			super.onFailure(e, errorResponse);
		}
	}


	/**
	 * 注册广播方法
	 */
	private void registerBroadcast() {
		//表名接收广播类型
		IntentFilter filter =
				new IntentFilter(UrgentSetActivity.LOGIN_ACTION);
		LocalBroadcastManager.getInstance(getApplicationContext())
				.registerReceiver(broadcast, filter);
	}
	/**
	 * 销毁广播，避免内存泄漏
	 */
	private void unregisterBroadcast() {
		LocalBroadcastManager.getInstance(getApplicationContext())
				.unregisterReceiver(broadcast);
	}

	@Override
	protected void onStart() {
		super.onStart();
		showWelcomeImage();
//		Log.e("zq","-----------"+pathBig);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterBroadcast();
	}

	private void initSDK() {
		mDSKernel = DSKernel.newInstance();
		mDSKernel.init(this, mConnCallback);
		showWelcomeImage();
	}
	IConnectionCallback mConnCallback = new IConnectionCallback() {// SDK链接状态回调
		@Override
		public void onDisConnect() {
		}

		@Override
		public void onConnected(final ConnState state) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
//					Toast.makeText(MainActivity.this, "state:"+state, Toast.LENGTH_LONG).show();
					switch (state) {
						case AIDL_CONN:
							//与本地service的连接畅通
							break;
						case VICE_SERVICE_CONN:
							//与副屏service连接畅通
							long fileId = SharedPreferencesUtil.getLong(MainActivity.this, SHOW_IMG_LIST_ID);
							long fileId1 = SharedPreferencesUtil.getLong(MainActivity.this, WELCOME_IMG_ID);
							long fileId2 = SharedPreferencesUtil.getLong(MainActivity.this,SHOW_VIDEO_LIST_DATA_ID);
							long fileId3 = SharedPreferencesUtil.getLong(MainActivity.this,SHOW_IMGS_LIST_DATA_ID);
							if(fileId2!=-1L)checkImg(fileId2,SHOW_VIDEO_LIST_DATA_ID);
							if(fileId3!=-1L)checkImg(fileId3,SHOW_IMGS_LIST_DATA_ID);
							if(fileId!=-1L)checkImg(fileId, SHOW_IMG_LIST_ID);
							if(fileId1!=-1L) checkImg(fileId1, WELCOME_IMG_ID);
							break;
						case VICE_APP_CONN:
							//与副屏app连接畅通
							break;

						default:
							break;
					}

				}
			});
		}
	};
	private void checkImg(long fileId, final String key){

		mDSKernel.checkFileExist(fileId, new ICheckFileCallback() {
			@Override
			public void onCheckFail() {
//				Toast.makeText(MainActivity.this, key + " 文件不存在", Toast.LENGTH_LONG).show();
			}

			@Override
			public void onResult(boolean b) {
				if(!b){
					SharedPreferencesUtil.put(MainActivity.this, key, -1L);
				}else{
//					Toast.makeText(MainActivity.this, key + " 文件存在", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
//    int i=0;
//	int y=0;
	private class TimeThread extends Thread{
		@Override
		public void run() {
			super.run();
//			Log.e("lh","i---"+(i++));
			while (isEndHandler==false) {
				try {
//					Log.e("lh","y---"+(y++));
					Thread.sleep(1 * 1000);
					Message msg = new Message();
					msg.what = 1;
					mHandler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	private Handler mHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case 1:
					long sysTime=System.currentTimeMillis();
					CharSequence timeStr= DateFormat.format("hh:mm:ss", sysTime);
					tv_time.setText(timeStr);
					break;
			}
		}
	};

	private void initRes() {
		rb_zaocan = (RadioButton) findViewById(R.id.rb_zaocan);
		rb_wucan = (RadioButton) findViewById(R.id.rb_wucan);
		rb_wancan = (RadioButton) findViewById(R.id.rb_wancan);
		rb_qucan = (RadioButton) findViewById(R.id.rb_qucan);
		rb_jiesuan = (RadioButton) findViewById(R.id.rb_jiesuan);
		rb_dingdan = (RadioButton) findViewById(R.id.rb_dingdan);
		rb_daying = (RadioButton) findViewById(R.id.rb_daying);
		rb_shezhi = (RadioButton) findViewById(R.id.rb_shezhi);
		tv_time= (TextView) findViewById(R.id.tv_time);
		tv_hint= (TextView) findViewById(R.id.tv_hint);

		//判断是否是紧急模式
		if(Constatus.URGENT_TYPE){
			tv_hint.setVisibility(View.VISIBLE);
		}
		registerBroadcast();

		new TimeThread().start();

//		classintent();
		
		
		String code = getIntent().getStringExtra("code");
		if (code!=null && code.equals("1")) {
			DingdanFragment dingdan = new DingdanFragment();
			MyFragmentReplace.fragmentReplace(MainActivity.this,
					R.id.fram_fanqiedingcan, dingdan);
			rb_dingdan.performClick();
			rb_dingdan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
			rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
			rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
			IS_CURRENT_PAGE=6;
//			rb_gouwuche.setChecked(true);
		}else {
			JiesuanFragment jiesuan = new JiesuanFragment();
			MyFragmentReplace.fragmentReplace(MainActivity.this,
					R.id.fram_fanqiedingcan, jiesuan);
			rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
			rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
			rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
			rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
		}
		setRbOnClick();
	}
	private void setRbOnClick() {
		rb_zaocan.setOnClickListener(rbOnClickListener);
		rb_wucan.setOnClickListener(rbOnClickListener);
		rb_wancan.setOnClickListener(rbOnClickListener);
		rb_qucan.setOnClickListener(rbOnClickListener);
		rb_jiesuan.setOnClickListener(rbOnClickListener);
		rb_dingdan.setOnClickListener(rbOnClickListener);
		rb_daying.setOnClickListener(rbOnClickListener);
		rb_shezhi.setOnClickListener(rbOnClickListener);
	}

	private OnClickListener rbOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// 早餐
			case R.id.rb_zaocan:
				if (IS_CURRENT_PAGE != 1) {
//					ZaocanFragment zaocan = new ZaocanFragment();
//					MyFragmentReplace.fragmentReplace(MainActivity.this,
//							R.id.fram_fanqiedingcan, zaocan);
//					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
//					IS_CURRENT_PAGE = 1;
//					startActivityForResult(intent, requestCode)
				}
				break;
			// 午餐
			case R.id.rb_wucan:
				if (IS_CURRENT_PAGE != 5) {
					 WucanFragment wucan = new WucanFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, wucan);
					rb_wucan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
					IS_CURRENT_PAGE = 5;
					
				}
				break;
				// 晚餐
			case R.id.rb_wancan:
				if (IS_CURRENT_PAGE != 3) {
//					WancanFragment wancan = new WancanFragment();
//					MyFragmentReplace.fragmentReplace(MainActivity.this,
//							R.id.fram_fanqiedingcan, wancan);
//					rb_wancan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
//					IS_CURRENT_PAGE = 3;
				}
				break;
			// 取餐
			case R.id.rb_qucan:
				if (IS_CURRENT_PAGE != 4) {
//					QucanFragment qucan = new QucanFragment();
//					MyFragmentReplace.fragmentReplace(MainActivity.this,
//							R.id.fram_fanqiedingcan, qucan);
//					rb_qucan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
//					IS_CURRENT_PAGE = 4;
				}
				break;
			// 结算
			case R.id.rb_jiesuan:
				if (IS_CURRENT_PAGE != 2) {
					JiesuanFragment jiesuan = new JiesuanFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, jiesuan);
					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
					rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
					IS_CURRENT_PAGE = 2;
				}
				break;
				// 订单
			case R.id.rb_dingdan:
				if (IS_CURRENT_PAGE != 6) {
					DingdanFragment dingdan = new DingdanFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, dingdan);
					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
					rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
					IS_CURRENT_PAGE = 6;
				}
				break;
				// 设置
			case R.id.rb_daying:
				if (IS_CURRENT_PAGE != 7) {
//					DayingFragment daying = new DayingFragment();
//					MyFragmentReplace.fragmentReplace(MainActivity.this,
//							R.id.fram_fanqiedingcan, daying);
//					rb_daying.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
//					rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
//					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.white));
//					IS_CURRENT_PAGE = 7;
				}
				break;
			// 设置
			case R.id.rb_shezhi:
				if (IS_CURRENT_PAGE != 8) {
					ShezhiFragment shezhi = new ShezhiFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, shezhi);
					rb_shezhi.setBackgroundColor(getResources().getColor(R.color.radiobutton_red));
					rb_wucan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_wancan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_qucan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_jiesuan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_dingdan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_zaocan.setBackgroundColor(getResources().getColor(R.color.white));
					rb_daying.setBackgroundColor(getResources().getColor(R.color.white));
					IS_CURRENT_PAGE = 8;
				}
				break;

			default:
				break;
			}

		}
	};

	private class  UrgentBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if(!Constatus.URGENT_TYPE){
				tv_hint.setVisibility(View.GONE);
			}else{
				tv_hint.setVisibility(View.VISIBLE);
			}
		}
	}
	
	private long exitTime = 0;


	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
	       super.onWindowFocusChanged(hasFocus);
	       if (hasFocus) {
	            View decorView = getWindow().getDecorView();
	                 decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
	                  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
	                  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
	                  |View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 
	                  |View.SYSTEM_UI_FLAG_FULLSCREEN);
	               }
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
	        if((System.currentTimeMillis()-exitTime) > 2000){  
	            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();                                
	            exitTime = System.currentTimeMillis();   
	        } else {
	            finish();
	            System.exit(0);
	        }
	        return true;   
	    }
	    return super.onKeyDown(keyCode, event);
	}


	private void showWelcomeImage() {
		taskId = SharedPreferencesUtil.getLong(this, WELCOME_IMG_ID);
		if (taskId != -1L) {
			showImgWelcome(taskId);
			return;
		}
		File file = new File(pathBig);
		if (!file.exists()) {
//			Toast.makeText(getApplicationContext(), "No file!", Toast.LENGTH_SHORT).show();
			return;
		}
		taskId = mDSKernel.sendFile(DSKernel.getDSDPackageName(), pathBig, new ISendCallback() {
			@Override
			public void onSendSuccess(long l) {
				showImgWelcome(taskId);
				SharedPreferencesUtil.put(getApplicationContext(), WELCOME_IMG_ID, taskId);
			}

			@Override
			public void onSendFail(int i, String s) {
			}

			@Override
			public void onSendProcess(long l, long l1) {
			}
		});
	}

	private void showImgWelcome(long taskId) {
		String json1 = UPacketFactory.createJson(DataModel.SHOW_IMG_WELCOME,"");
		mDSKernel.sendCMD(DSKernel.getDSDPackageName(),json1,taskId,null);
	}
}
